package com.addict.applocker.util;

import android.util.Log;

import com.addict.applocker.Data.AppListItem;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;

/**
 * 冻结软件工具类
 * - 依旧的单例，因为获取Root权限之后
 * - 为了保证运行速度，重用Process，所以就只能单例了咯
 */
public class FreezeUtil {
    private Process mSuProcess = null;
    private DataOutputStream suOut = null;
    private DataInputStream suIn = null;

    private static FreezeUtil me = null;
    private FreezeUtil() {};

    public static FreezeUtil getInstance() throws Exception {
        if(me == null) {
            me = new FreezeUtil();
            try {
                me.mSuProcess = Runtime.getRuntime().exec("su");
                me.suOut = new DataOutputStream(me.mSuProcess.getOutputStream());
                me.suIn = new DataInputStream(me.mSuProcess.getInputStream());
            } catch (IOException e) {
                Log.e("Debug:FreezeUitl", "获取Root权限出错！");
                me.onDestroy();
                throw new Exception("获取Root失败！");
            }
        }
        return me;
    }

    public void onDestroy() {
        try {
            if(suOut != null) {
                suOut.writeBytes("exit\n");
                suOut.flush();
                suOut.close();
            }
            if(suIn != null) {
                suIn.close();
            }
        } catch (Exception e) {}
    }

    public boolean disableApp(String appPackageName) {
        try {
            suOut.writeBytes("pm disable " + appPackageName + "\n");
            suOut.flush();

            /*String line = null;
            while ((line = suIn.readLine()) != null) {
                Log.e("Debug:FreezeUtil", line);
                if(line.indexOf("disable") != -1) {
                    return true;
                }else {
                    return false;
                }
            }*/

        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean enableApp(String appPackageName) {
        try {
            suOut.writeBytes("pm enable " + appPackageName + "\n");
            suOut.flush();

            /*String line = null;
            while ((line = suIn.readLine()) != null) {
                Log.e("Debug:FreezeUtil", line);
                if(line.indexOf("enable") != -1) {
                    return true;
                }else {
                    return false;
                }
            }*/
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
/*
    public void FreezeAppArray(ArrayList<AppListItem> array) {

    }*/
}
